import asyncio
import random
import uvicorn
from   fastapi           import FastAPI
from   fastapi.responses import StreamingResponse

app = FastAPI()

headers = {'content-type': 'application/json; charset=utf-8'}

async def stream_response():
    text = "这是一个逐步生成的文本，模拟大模型的输出。"
    cursor = 0
    while cursor < len(text):
        rnd      = random.randint(1, 3)
        str_rtn  = text[cursor: min(cursor+rnd, len(text))]
        cursor   += rnd
        yield f"{str_rtn}"  
        await asyncio.sleep(0.2)                # 模拟异步操作


@app.get("/stream")
async def read_stream():
    return StreamingResponse(stream_response(), 
                             media_type="text/event-stream", 
                             headers=headers)


if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=8000)